package com.hui.platform.falseworkapi.common.security.jwt;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hui.platform.falseworkapi.common.security.base.IUserDetailsProvider;
import com.hui.platform.falseworkapi.service.business.user.entity.TbAuthorities;
import com.hui.platform.falseworkapi.service.business.user.entity.TbUser;
import com.hui.platform.falseworkapi.service.business.user.service.TbAuthoritiesService;
import com.hui.platform.falseworkapi.service.business.user.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 整合用户验证提供者
 *
 * @author hui
 * @date 2020/1/14
 */
@Component
public class UserDetailsProvider implements IUserDetailsProvider {

    @Autowired
    @Lazy
    private TbUserService tbUserService;

    @Autowired
    @Lazy
    private TbAuthoritiesService tbAuthoritiesService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TbUser tbUser = tbUserService.getOne(new LambdaQueryWrapper<TbUser>().eq(TbUser::getUsername, username));
        if (tbUser != null){
            List<String> auths = tbAuthoritiesService.list(new LambdaQueryWrapper<TbAuthorities>().eq(TbAuthorities::getUserId, tbUser.getId()))
                    .stream()
                    .map(TbAuthorities::getAuthroity)
                    .collect(Collectors.toList());

            List<GrantedAuthority> grantAuths = new ArrayList<>();
            if (auths != null && auths.size() > 0){
                for (String auth : auths){
                    grantAuths.add(new SimpleGrantedAuthority(auth));
                }
            }
            grantAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
            return new User(username, tbUser.getPassword(), grantAuths);
        }
        throw new UsernameNotFoundException(String.format("Can not found the user： '%s'.", username));
    }

    @Override
    public boolean supported(String username) {
        return true;
    }
}
